var util = require("../../utils/utils.js");
var app = getApp();
Page({
  data:{
    inTheaters:{},
    comingSoon:{},
    top250:{},
    searchResult:{},
    containerShow:true,
    searchPannelShow: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var inTheatersUrl = app.globalData.doubanData + '/movie-intheaters.json';
    var comingSoonUrl = app.globalData.doubanData + '/movie-coming-soon.json';
    var top250Url = app.globalData.doubanData + '/movie-top250.json';
    this.getMovieListData(inTheatersUrl, "inTheaters", "正在热映");
    this.getMovieListData(comingSoonUrl, "comingSoon", "即将上映");
    this.getMovieListData(top250Url, "top250", "豆瓣TOP250");
  },

  onMoreTap: function (event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category=' + category,
    })
  },

  onMovieTap: function (event){
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id=' + movieId,
    })
  },

  getMovieListData: function (url, settledKey, categoryTitle){
    var that = this;
    wx.request({
      url: url,
      data: {},
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data);
        //success
        that.processDoubanData(res.data, settledKey, categoryTitle);
      },
      fail: function () {
        //fail
        console.log("fail");
      },
      complete: function () {
        //complete
        console.log("complete");
      }
    })
  },

  onCancelImgTap:function(){
    this.setData({
      containerShow: true,
      searchPannelShow: false,
      searchResult:{}
    })
  },

  onBindFocus:function(event){
    this.setData({
      containerShow: false,
      searchPannelShow: true
    })
  },
  onBlur: function (event){
    var text = event.detail.value;
    var searchUrl = app.globalData.doubanDomain + "/v2/movie/search?q=" + text;
    this.getMovieListData(searchUrl, "searchResult", "");
  },

  processDoubanData: function (moviesDouban, settledKey, categoryTitle){
    var count = 3;
    if (settledKey == "searchResult") { count = moviesDouban.subjects.length;}
    var movies = [];
    for (var i = 0; i < count;i++){
      var subject = moviesDouban.subjects[i];
      var title = subject.title;
      if (title.length > 6) {
        title = title.substring(0, 6) + "...";
      }
      var temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      };
      movies.push(temp); 
    }
    var readyData = {};
    readyData[settledKey] = {
      categoryTitle: categoryTitle,
      movies: movies
    }

    console.log(readyData);
    this.setData(readyData);
  }
})